import re
from rest_framework.views import APIView
from . import serializers,models
from utils.response import APIResponse



class LoginApiView(APIView):
    # 认证权限一定要局部禁用,因为权限认证一般是在用户登入后获取用户信息才进行的认证
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.LoginModelSerializer(data=request.data)
        #数据校验,生成一个序列化类的对象
        serializer.is_valid(raise_exception=True)  # 内部在全局钩子中完成token的签发
        return APIResponse(results={
            'username': serializer.content.get('user').username,
            'token': serializer.content.get('token'),
            'ico': serializer.content.get('icon')
        })


# 账号验证是否注册了

class Verify_Username(APIView):
    def get(self, request, *args, **kwargs):
        username = request.query_params.get("username")
        try:
            # 只要数据库有，就代表已注册
            models.User.objects.get(username=username)
            return APIResponse(2, msg='账号已注册')
        except:
            return APIResponse(0, msg='账号未注册')

class Verify_Mobile(APIView):
    def get(self, request, *args, **kwargs):
        mobile = request.query_params.get("mobile")
        try:
            # 只要数据库有，就代表已注册
            models.User.objects.get(mobile=mobile)
            return APIResponse(2, msg='手机号已注册')
        except:
            return APIResponse(0, msg='手机号未注册')



class RegisterUserAPIView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = serializers.RegisterUserModelSerializer(data=request.data)
        # 数据校验,生成一个序列化类的对象
        serializer.is_valid(raise_exception=True)
        #新增数据,如user对象
        user_obj = serializer.save()
        #将user对象序列化给前端
        return APIResponse(results=serializers.RegisterUserModelSerializer(user_obj).data)

class ChangeUserAPIView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = serializers.ChangeUserModelSerializer(data=request.data)
        # 数据校验,生成一个序列化类的对象
        serializer.is_valid(raise_exception=True)
        return APIResponse(results={'username':serializer.content.get('user').username,})